/****************************************************************************
 * lsrv2.c  
 * License server server program version 2
 */
 
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<signal.h>
#include<sys/errno.h>
#define MSGLEN		1280		/* Size of our datagrams */
#define RECLAIM_INTERVAL 10             /*reclaim interval*/
int Max;
extern license[10];
 
int main(int ac, char *av[])
{
               /*get a license
                * username:User   password:Pass  type:10/50
                  send_msg like: username password type */
              int flag=0;
             if(strncmp(av[1],"User",4)==0&&strncmp(av[2],"Pass",4)==0)
             {
                flag=1;
                Max=atoi(av[3]);
                if(Max==10) printf("you applied for a 10 person licnese\n");
                else if(Max==50) printf("you applied for a 50 person licnese\n");
                else {
                	printf("ERROR license type wrong");
                	flag=0;
				}
                  
                if(flag==1) printf("your license :%s\n",license);
             }
             else printf("FAIL username or password incorrect\n");

	struct sockaddr_in client_addr;
                socklen_t addrlen;
	char      buf[MSGLEN];
	int ret;
	int       sock;
                void ticket_reclaim();
               unsigned time_left;

	sock = setup();
               signal(SIGALRM,ticket_reclaim);
                alarm(RECLAIM_INTERVAL);
	while(flag) {
		addrlen = sizeof(client_addr);
		ret = recvfrom(sock,buf,MSGLEN,0,
				(struct sockaddr*)&client_addr,&addrlen);
		if ( ret != -1 ){
			buf[ret] = '\0';
			narrate("GOT:", buf, &client_addr);
                                                time_left=alarm(0);
			handle_request(buf,&client_addr,addrlen);
                                                alarm(time_left);
		}
		else if ( errno != EINTR )
			perror("recvfrom");
	}
}
